package cn.zjh.user.service.impl;

import cn.zjh.basic.constant.VerifyCodeConstants;
import cn.zjh.basic.exception.BusinessException;
import cn.zjh.basic.util.MD5Utils;
import cn.zjh.basic.util.StrUtils;
import cn.zjh.org.domain.Employee;
import cn.zjh.user.domain.Logininfo;
import cn.zjh.user.domain.User;
import cn.zjh.user.dto.UserDto;
import cn.zjh.user.mapper.LogininfoMapper;
import cn.zjh.user.mapper.UserMapper;
import cn.zjh.user.service.IUserService;
import cn.zjh.basic.service.impl.BaseServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private JavaMailSender javaMailSender;


    /**
     * 手机注册用户
     * @param userDto
     */
    @Override
    public void phoneRegister(UserDto userDto) {

        String phone = userDto.getPhone();
        String imageCodeKey = userDto.getImageCodeKey();
        String password = userDto.getPassword();
        String passwordRepeat = userDto.getPasswordRepeat();

       //空值校验
      if(StringUtils.isEmpty(phone)
            || StringUtils.isEmpty(imageCodeKey)
            || StringUtils.isEmpty(password)
            || StringUtils.isEmpty(passwordRepeat)){
          throw new BusinessException("请输入正确的数据!!!");
    }

    //两次密码是否相同
        if(!password.equals(passwordRepeat)){
        throw new BusinessException("两次密码不一致!!!");
    }
        //验证码是否过期
        Object obj = redisTemplate.opsForValue().get(VerifyCodeConstants.REGISTER_CODE_PREFIX + phone);
        if(obj == null){
        throw new BusinessException("验证码无效，请重新获取!!!");
    }

        //验证码是否正确
        String codeTmp = obj.toString().split(":")[0];
            if(!codeTmp.equalsIgnoreCase(imageCodeKey)){
        throw new BusinessException("验证码错误!!!");
    }

        //保存数据
        //先保存t_logininfo
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);

        logininfoMapper.save(logininfo);//自增
        //再保存t_user
        user.setLogininfoId(logininfo.getId());
        //user.setLogininfo(logininfo);
        userMapper.save(user);
    }

    /**
     * 邮箱注册用户
     * @param userDto
     */
    @Override
    public void emailRegister(UserDto userDto) throws MessagingException {
        //获取前端数据
        String email = userDto.getEmail();
        String password = userDto.getQpassword();
        String passwordRepeat = userDto.getQpasswordRepeat();

        if (StringUtils.isEmpty(email)
            ||StringUtils.isEmpty(password)
                ||StringUtils.isEmpty(passwordRepeat)){
            throw new BusinessException("数据不能为空");
        }
        System.out.println(email+"===========+");
        //校检密码是否一致
        if (!password.equals(passwordRepeat)){
            throw new BusinessException("密码不一样");
        }

        //保存数据
        //先保存t_logininfo
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);

        logininfoMapper.save(logininfo);//自增
        //再保存t_user
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);


        //发送邮箱让用户激活
        //发送邮件：审核通过邮件 - 叫他激活
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
        //设置发送方
        helper.setFrom("1028465808@qq.com");
        //设置主题
        helper.setSubject("店铺激活邮件");
        //设置内容
        helper.setText("<h1>你的店铺已经注册!!!</h1>" +
                "<a href='http://172.16.10.186:8080/user/active/"+user.getId()+"'>点击该链接激活</a>",true);
        //设置收件人http://127.0.0.1:80
        User user1 = userMapper.findOne(user.getId());
        helper.setTo("1028465808@qq.com");
        //发送
        javaMailSender.send(mimeMessage);
    }

    /**
     * 修改状态
     * @param id
     */
    @Override
    public void active(Long id) {
        User user = userMapper.findOne(id);
        user.setState(1);
        userMapper.upDate(user);
    }


    private User userDto2User(UserDto userDto) {
        User user = new User();
        BeanUtils.copyProperties(userDto,user);
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Pwd = MD5Utils.encrypByMd5(userDto.getPassword()+salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
}

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //按照同名属性赋值【username，email，phone，salt，password】
        BeanUtils.copyProperties(user,logininfo);
        //当前对象是用户
        logininfo.setType(1);
        return logininfo;
    }
}